﻿using System.Linq;
using EPiAbstractions.Common.Categories;
using EPiServer.Common.Categories;
using JoelAbrahamsson.MetaWeblog;
using Moq;
using StructureMap.AutoMocking;
using Xunit;

namespace JoelAbrahamsson.BlogExtensions.Tests.BlogCategoryProviderTests
{
    public class GetBlogCategoriesTests
    {
        [Fact]
        public void GetBlogCategories_ReturnsGrandChildrenOfRootCategory()
        {
            Mock<ICategory> fakeRootCategory = new Mock<ICategory>();
            Mock<ICategory> fakeChildOfRootCategory = new Mock<ICategory>();
            Mock<ICategory> fakeSecondChildOfRootCategory = new Mock<ICategory>();
            Mock<ICategory> fakeGrandChildOfRootCategory = new Mock<ICategory>();
            fakeGrandChildOfRootCategory.Setup(category => category.ID).Returns(1);
            fakeGrandChildOfRootCategory.Setup(category => category.Parent).Returns(fakeChildOfRootCategory.Object);
            Mock<ICategory> fakeSecondGrandChildOfRootCategory = new Mock<ICategory>();
            fakeSecondGrandChildOfRootCategory.Setup(category => category.ID).Returns(2);
            fakeSecondGrandChildOfRootCategory.Setup(category => category.Parent).Returns(fakeSecondGrandChildOfRootCategory.Object);
            MoqAutoMocker<BlogCategoryProvider> categoryProviderAutoMocker = new MoqAutoMocker<BlogCategoryProvider>(); 
            categoryProviderAutoMocker.PartialMockTheClassUnderTest();
            Mock<ICategoryHandlerFacade> fakeCategoryHandlerFacade = Mock.Get(categoryProviderAutoMocker.Get<ICategoryHandlerFacade>());
            Mock.Get(categoryProviderAutoMocker.ClassUnderTest).Setup(provider => provider.BlogCategoriesRoot).Returns(fakeRootCategory.Object);
            fakeCategoryHandlerFacade.Setup(
                handler => handler.GetCategories(fakeRootCategory.Object)).Returns(
                new CategoryCollection { fakeChildOfRootCategory.Object, fakeSecondChildOfRootCategory.Object });
            CategoryCollection grandChildren = new CategoryCollection { fakeGrandChildOfRootCategory.Object, fakeSecondGrandChildOfRootCategory.Object };
            fakeCategoryHandlerFacade.Setup(
                handler => handler.GetCategories(fakeChildOfRootCategory.Object)).Returns(new CategoryCollection { fakeGrandChildOfRootCategory.Object });
            fakeCategoryHandlerFacade.Setup(
                handler => handler.GetCategories(fakeSecondChildOfRootCategory.Object)).Returns(new CategoryCollection { fakeSecondGrandChildOfRootCategory.Object });

            CategoryInfo[] returnedCategories = categoryProviderAutoMocker.ClassUnderTest.GetBlogCategories(null);

            Assert.NotNull(returnedCategories);
            foreach (ICategory category in grandChildren)
            {
                Assert.Equal<int>(1, returnedCategories.Count(categoryInfo => categoryInfo.categoryid == category.ID.ToString()));
            }
            
        }
    }
}